package net.elive.server;

import java.io.IOException;
import java.net.DatagramPacket;

import net.elive.utils.LogUtils;

import org.apache.commons.logging.Log;

/**
 * 消息接收线程
 * @author Administrator
 *
 */
public class MessageReceiver implements Runnable {
	Log log = LogUtils.getLog(MessageReceiver.class);
	private Thread thread;
	Object runOb=new Object();
	public  MessageReceiver() {
		thread = new Thread(this);
		thread.start();
	}
	@Override
	public void run(){
		while(true){
			byte[] data = new byte[1024];
			DatagramPacket dp = new DatagramPacket(data,data.length);
			try{
				Config.ds.receive(dp);		//服务器端接收数据包
				log.info(">>>>>>>>>>>>>>>服务正在接收数据中>>>>>>>>>>>>>>>");
			}catch(IOException e){
				e.printStackTrace();
				continue;
			}
			/**
			 * 将接收数据包加入消息队列
			 */
			Config.messageQueue.add(dp);
			synchronized (runOb){
				if(Config.run&&Config.messageQueue.size()!=0){
					runOb.notify();
				}
			}
		}
	}
	/**
	 * 获取数据包
	 * @return
	 */
	DatagramPacket getPacket(){
		synchronized (runOb){
			if(Config.messageQueue.size()==0||!Config.run){
				try {
					runOb.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			DatagramPacket dp=Config.messageQueue.get(0);
			DatagramPacket dp2=null;
			if(dp!=null){
				dp2=new DatagramPacket(dp.getData(),dp.getLength());
				dp2.setAddress(dp.getAddress());
				dp2.setPort(dp.getPort());
			}
			
			Config.messageQueue.remove(0);
			return dp2;
		}
	}
	
	void pause(){
		Config.run=false;
	}
	
	void play(){
		synchronized (runOb){
			Config.run=true;
			if(Config.messageQueue.size()!=0){
				runOb.notify();
			}
		}
	}
}
